﻿

using EasyModbus;
using IntelligentEscalator.Tools;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Timer = System.Timers.Timer;

namespace IntelligentEscalator.Helper
{
    public class CKHelper : IHostedService
    {
        private bool Connected = false;
        ModbusClient modbusClient = null;
        IConfiguration config = ConfigurationManagerHelper.Configuration;
        public Task StartAsync(CancellationToken cancellationToken)
        {
            Timer _outTimer = new Timer(5000);
            _outTimer.Elapsed += _outTimer_Elapsed;
            _outTimer.Start();
           

            Timer loopTimer = new Timer(int.Parse(config.GetSection("CKTimer").Value));
            loopTimer.Elapsed += LoopTimer_Elapsed;
            loopTimer.Start();


            return Task.CompletedTask;
        }

        private void LoopTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            ExcuteTask();
        }

        private void _outTimer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            if (!Connected) {
                Connect();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        
        }
        // 连接设备
        public void Connect() {
            string ipAddress = config.GetSection("LocalIP").Value; // Modbus TCP服务器IP地址
            int port = 502;                     // Modbus TCP端口号（默认为502）
            byte unitId = 1;                    // Modbus设备ID

            // 创建Modbus TCP客户端
            modbusClient = new ModbusClient(ipAddress, port);
            modbusClient.UnitIdentifier = unitId;
            try
            {
                // 连接到Modbus TCP服务器
                modbusClient.Connect();
                Connected = true;
                // 打开数据发送定时器
            }
            catch (Exception ex)
            {
                Connected = false;
                modbusClient = null;
                LogHelper.Error($"CK设备连接异常{ex.Message}");
            }
        }

        public void ExcuteTask()
        {
            if (modbusClient != null && modbusClient.Connected)
            {
                // 读取寄存器
                int[] registers = modbusClient.ReadHoldingRegisters(96, 16); // 从地址0开始读取10个寄存器
                foreach (int register in registers)
                {
                    Console.WriteLine(Math.Round(register/1000.0,2)); // 以16进制格式输出寄存器值
                }

            }
        }
    }
}
